/*
 * CastDRAndroid
 * Copyright (c) 2014 Christian Holm Christensen
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 *
 */
package org.cholm.media.castdr.fragments;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import org.cholm.media.castdr.Activity;
import org.cholm.media.castdr.R;
import org.cholm.media.castdr.adapters.LiveAdapter;
import org.cholm.media.castdr.backend.Category;
import org.cholm.media.castdr.backend.Extractor;
import org.cholm.media.castdr.backend.LiveChannel;
import org.cholm.media.castdr.loaders.LiveLoader;
import org.cholm.media.castdr.LogUtils; import static org.cholm.media.castdr.LogUtils.LOGd;
import static org.cholm.media.castdr.LogUtils.LOGw;
/**
 * Live channels
 * <p/>
 * Note, this implements the selection listener to react to clicks
 *
 * @author cholm
 */
public class LiveFragment extends Fragment implements
        LiveAdapter.OnSelectionListener {
    /**
     * Debug TAG
     */
    private static final String TAG = LogUtils.makeLogTag(LiveFragment.class);
    /**
     * Save category ID
     */
    private IdSaver mCatSaver = new IdSaver(TAG + ":Category");
    private IdSaver mSubSaver =
            new IdSaver(TAG
                    + ":SubCategory");
    /**
     * Target live channel
     */
    private LiveChannel mTarget = null;
    /**
     * Top-view
     */
    private View mView = null;
    /**
     * Listview
     */
    private ListView mList = null;
    /**
     * The adapter
     */
    private LiveAdapter mAdapter = null;
    /**
     * If true, then show title
     */
    private boolean mEnableTitle = true;

    /**
     * Constructor
     */
    public LiveFragment() {
    }

    /**
     * Set the sub-category
     *
     * @param tgt
     */
    public void setTarget(int cat, int sub) {
        mCatSaver.setId(cat);
        mSubSaver.setId(sub);
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            mCatSaver.restore(savedInstanceState);
            mSubSaver.restore(savedInstanceState);
        }
    }

    /**
     * Create our view
     */
    public View onCreateView(LayoutInflater inflator, ViewGroup container,
                             Bundle savedInstance) {
        int catId = mCatSaver.getId();
        int subId = mSubSaver.getId();
        if (catId < 0 || subId < 0) {
            LOGw(TAG, "Ids invalid: " + catId + "/" + subId);
            return null;
        }
        Category cat = Extractor.instance().getList().get(catId);
        if (cat == null) {
            LOGw(TAG, "No category found");
            return null;
        }

        mTarget = (LiveChannel) cat.getSub(subId);
        if (mTarget == null) {
            LOGw(TAG, "No sub-category found in " + cat.getName());
            return null;
        }

        mView = inflator.inflate(R.layout.live_top, container, false);
        LOGd(TAG, "Created activity");

        // Message handler
        mList = (ListView) mView.findViewById(R.id.listView);
        mAdapter = new LiveAdapter(this.getActivity());
        mAdapter.setListener(this);
        mList.setEmptyView(mView.findViewById(R.id.progress));

        if (mTarget != null) {
            TextView sub = (TextView) mView.findViewById(R.id.subTitle);
            if (mEnableTitle) {
                sub.setText(mTarget.getName());
            } else sub.setVisibility(View.GONE);
        }
        LOGd(TAG, "Setting adapter");
        mList.setAdapter(mAdapter);
        // setListShown(false);

        LOGd(TAG, "Initialize the loader");
        getActivity().getSupportLoaderManager()
                .restartLoader(R.integer.live_loader,
                        null,
                        new LiveCallback());

        return mView;
    }

    @Override
    public void onDestroyView() {
        LOGd(TAG, "Destroying subFragment: " + mTarget.getName());
        super.onDestroyView();
        mCatSaver.save();
        mSubSaver.save();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        LOGd(TAG, "Saving instance state " + mCatSaver.getId() + "/"
                + mSubSaver.getId());
        mCatSaver.save(outState);
        mSubSaver.save(outState);
        super.onSaveInstanceState(outState);
    }

    /**
     * When selecting the channel
     */
    @Override
    public void onSelect(LiveChannel lc) {
        Activity a = (Activity) getActivity();
        a.playLive(lc);
    }

    /**
     * Enable title in the view
     *
     * @param enable If true, enable title display
     */
    public void setEnableTitle(boolean enable) {
        mEnableTitle = enable;
    }

    /**
     * Call-backs from loader
     *
     * @author cholm
     */
    private class LiveCallback implements
            LoaderManager.LoaderCallbacks<LiveChannel> {
        /**
         * Debug TAG
         */
        private final String TAG = LogUtils.makeLogTag("LiveFragment" +
                ".LiveCallback");

        /**
         * Create the loader
         */
        @Override
        public Loader<LiveChannel> onCreateLoader(int arg0, Bundle arg1) {
            LOGd(TAG, "Creating loader");
            return new LiveLoader(getActivity(), mTarget);
        }

        /**
         * When finished
         */
        @Override
        public void onLoadFinished(Loader<LiveChannel> ldr, LiveChannel data) {
            LOGd(TAG, "Loader finished " + data);
            // Set data on adapter
            mAdapter.setData(data);
            // Let it know that the content changed
            if (data != null) mAdapter.notifyDataSetChanged();
            else mAdapter.notifyDataSetInvalidated();
            // Remove the empty view of the list
            mList.setEmptyView(mView.findViewById(R.id.emptyText));
            ldr.stopLoading();
        }

        /**
         * When resetting
         */
        @Override
        public void onLoaderReset(Loader<LiveChannel> arg0) {
            LOGd(TAG, "Reset loader");
        }

    }
}
// EOF
